import { call, put, fork, select, take } from 'redux-saga/effects'
import actions,{ GET_DATA, UPDATE_DATA } from '@/actions/individuationSetting'
import api from '@/api/individuationSetting'
import { message } from 'antd'
import util from '@/utils'
import successDesc from '@/constants/success'

function* getData() {
  try {
    const { isSuccess, data, desc } = yield call(api.getUserInfo)
    if(isSuccess && data){
      yield put(actions.getDataSuccess(data))
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.getDataFail())
    message.error(error.message || '获取数据错误')
  }
}

function* updateData() {
  try {
    const params = yield select(({ individuationSettingReducer }) => util.pick(individuationSettingReducer,[
      'ip',
      'receiveUrl',
      'remindPhone',
      'remindValue',
    ]))
    const { isSuccess, desc } = yield call(api.updateUserInfo, params)
    if(isSuccess){
      yield put(actions.updateDataSuccess())
      message.success(successDesc.save)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.updateDataFail())
    message.error(error.message || '更新错误')
  }
}

function* watchUpdateData() {
  while (true) {
    yield take(UPDATE_DATA)
    yield call(updateData)
  }
}

function* watchGetData() {
  while (true) {
    yield take(GET_DATA)
    yield call(getData)
  }
}

export default [
  fork(watchGetData),
  fork(watchUpdateData),
]